﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using LINQPad.Extensibility.DataContext;

namespace LINQPadDriverHelper
{
  [Serializable]
  public class DriverConfig
  {
    public readonly List<string> Assemblies = new List<string>();
    public readonly string FactoryAssembly;
    public readonly string FactoryType;
    public readonly string FactoryMehod;
    public readonly BuildMode Mode;
    public readonly string ConfigDomainName;

    public DriverConfig(XElement xml)
    {
      XElement assemblies = xml.Element("Assemblies");
      if (assemblies != null)
        Assemblies = assemblies.Value.Split(new[]{Path.PathSeparator}, StringSplitOptions.RemoveEmptyEntries).ToList();
      var modeElement = xml.Element("Mode");
      if (modeElement != null)
      {
        Mode = (BuildMode)Enum.Parse(typeof(BuildMode), (string)modeElement);
        if (Mode == BuildMode.FromConfig) {
          ConfigDomainName = (string) xml.Element("DomainName");
        }
        else
        {
          XElement factory = xml.Element("Factory");
          Debug.Assert(factory!=null, "factory != null");
          FactoryAssembly = (string)factory.Element("Assembly");
          FactoryType = (string)factory.Element("Type");
          FactoryMehod = (string)factory.Element("Method");
        }
      }
    }

    public static DriverConfig Get(IConnectionInfo cxInfo)
    {
      var config = new DriverConfig(cxInfo.DriverData);
      return config;
    }
  }
}